<template>
    <div>
        <div>
            <el-form class="form-box" ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="24" class="margin-bottom-0">
                        <el-form-item label="收款金额：" prop="salaAmt">
                            <div class="salaAmt">{{ unpay }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" class="margin-bottom-0">
                        <el-form-item label="会员验证：" prop="mobile">
                            <el-input v-model="form.mobile" placeholder="扫会员码/输入手机号、会员卡号" @focus="focusForm('mobile')"
                                @blur="blurForm" />
                            <div class="vip-info-box">客户姓名：{{ vip.name || '--' }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                电话：{{ vip.mobile || '--' }}</div>
                            <el-button class="search-btn" text @click="handleSearch">验证</el-button>
                            <img class="qrcode-img" @click="handleCode"
                                src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/vip/qrcode.png" alt="">
                        </el-form-item>
                    </el-col>

                    <el-col :span="24" class="margin-bottom-0">
                        <el-form-item label="会员卡号：" prop="cardNo">
                            <el-select v-model="form.cardNo" @change="changeCardNo">
                                <el-option v-for="item in card_options" :key="item.cardNo" :value="item.cardNo"
                                    :label="`${item.cardName}：No.${item.cardNo}`" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <div :class="{'not-info-vip':card_options.length < 1}"></div>
                    <div class="vip-info-box pd-vip-info"  v-if="card_options.length > 0 ">
                              <div class="pd-vip-contiantr">
                                <div>
                                本金：<span class="color-FF3333">{{ card_options.length > 0 ?
                                    card_options[currentCardIndex].currentAmt : '--' }}</span>
                              </div>
                                <div>
                                    赠送金额：<span class="color-FF3333">{{ card_options.length > 0 ?
                                    card_options[currentCardIndex].currentPresentAmt : '--' }}</span>
                                </div>
                                <div>
                                    金币：<span class="color-FF3333">{{ card_options.length > 0
                                    ? card_options[currentCardIndex].currentCoins : '--' }}</span>
                                </div>
                              </div>
                                <div>
                                    积分：<span class="color-FF3333">{{ card_options.length > 0
                                    ? card_options[currentCardIndex].currentPoint : '--' }}</span>
                                </div>
                            </div>
                    <el-col :span="24">
                        <el-form-item  class="jt-mt-tar" label="优惠券：" prop="ticketCode">
                            <el-input v-model="form.ticketName" placeholder="点击选择优惠券" @click="handleTicket" />
                            <!-- <el-select v-model="form.ticketCode">
                            <el-option v-for="item in ticket_options" :key="item.code" :value="item.code"
                                :label="item.ticketName" />
                        </el-select> -->
                            <!-- <div class="vip-info-box color-FF6A00">
                            优惠券已抵扣金额: {{ checkedAmt }}元
                        </div> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <div style="display: flex;align-items: center;position: relative;">
                            <el-form-item class="jt-mt-tar jt-mt-tar2" label="金币金额：" prop="payAmt">
                            <el-input v-model="form.payAmt_coins" placeholder="请输入金额" @focus="focusForm('payAmt')"
                                @blur="blurForm('coin')" clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                        </el-form-item>
                        <el-form-item class="jt-mt-text" label="" prop="">
                            可抵扣：<span class="color-FF3333">{{ coinsPrice }}</span>，非必填
                        </el-form-item>
                        </div>
                   
                    </el-col>
                    <!-- <el-col :span="12">
                        

                    </el-col> -->
                    <el-col :span="24">
                        <el-form-item class="jt-mt-tar" label="收取金额：" prop="payAmt">
                            <el-input v-model="form.payAmt" placeholder="请输入金额" @focus="focusForm('payAmt')"
                                @blur="blurForm('member')" clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 优惠券弹窗 -->
        <div class="dialog-box">
            <el-dialog v-model="ticketVisible" title="" top="80px" :show-close="false" :before-close="handleCancel">
                <div class="dialog-content">
                    <!-- 可用券 -->
                    <div class="dialog-title-row">
                        <div class="title">可选券 <span class="num">（{{ canUseNum }}张）</span></div>
                        <div class="tip">
                            <span>已选 <span class="color-FF6A00">{{ checkedList.length }}</span> 张</span>
                            <span class="margin-left-40">已抵扣金额 <span class="color-FF6A00">{{ checkedAmt }}</span> 元</span>
                        </div>
                    </div>
                    <div class="ticket-content">
                        <div class="ticket-box">
                            <template v-for="(item, index) in ticket_options">
                                <div class="ticket cursor-pointer" @click.prevent="handleCheckedTicket(item)" :key="index"
                                    v-if="item.isUse">
                                    <div class="ticket-name-box">
                                        <div class="ticket-type">{{ item.typeCodeName }}</div>
                                        <div v-if="item.typeCodeName == '兑换券'"
                                            class="ticket-wares font-size-24 color-FF3333">{{
                                                item.ticketName }}</div>
                                        <div v-else-if="item.typeCodeName == '优惠券'" class="ticket-num color-FF3333"><span
                                                class="font-size-48 ">{{ item.ticketAmt
                                                }}</span>元</div>
                                        <div v-else-if="item.typeCodeName == '折扣券'" class="ticket-num color-FF3333"><span
                                                class="font-size-48 ">{{ item.discounts
                                                }}</span>折</div>
                                    </div>
                                    <div class="divider"></div>
                                    <div class="info-box">
                                        <div>有效期：{{ item.startData }} 至 {{ item.endData }} </div>
                                        <div v-if="item.typeCodeName == '兑换券'">兑换物品：{{ item.goodsName }}</div>
                                        <div>使用限制：
                                            <span class="color-FF6A00" v-if="item.priceUseCondition == '0'">任意金额可用，</span>
                                            <span class="color-FF6A00" v-else-if="item.priceUseCondition == '1'">满{{
                                                item.useAmt
                                            }}可用，</span>
                                            <span class="color-FF6A00" v-else-if="item.priceUseCondition == '2'">每满{{
                                                item.useAmt }}可用，</span>
                                            <span class="color-FF6A00" v-if="item.useCondition == 0">无限制</span>
                                            <span class="color-FF6A00" v-else-if="item.useCondition == 1">每张桌台限用{{
                                                item.roomUseNum
                                            }}张</span>
                                            <span class="color-FF6A00" v-else-if="item.useCondition == 2">每个会员限用{{
                                                item.memberUseNum
                                            }}张</span>
                                            <span> ，优惠{{ item.isDiscountSharing == "1" ? '不' : '' }}可共享</span>
                                        </div>
                                    </div>

                                    <div class="check-box">
                                        <el-checkbox v-model="item.checked"></el-checkbox>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <!-- 不可用券 -->
                        <div class="dialog-title-row margin-top-10">
                            <div class="title">不可选券 <span class="num">（{{ cannotUseNum }}张）</span></div>
                        </div>
                        <div class="ticket-box unUse">
                            <template v-for="(item, index) in ticket_options">
                                <div class="ticket" :key="index" v-if="!item.isUse">
                                    <div class="ticket-name-box">
                                        <div class="ticket-type">{{ item.typeCodeName }}</div>
                                        <div v-if="item.typeCodeName == '兑换券'"
                                            class="ticket-wares font-size-24 color-FF3333">{{
                                                item.goodsName }}</div>
                                        <div v-else-if="item.typeCodeName == '优惠券'" class="ticket-num color-FF3333"><span
                                                class="font-size-48 ">{{ item.ticketAmt
                                                }}</span>元</div>
                                        <div v-else-if="item.typeCodeName == '折扣券'" class="ticket-num color-FF3333"><span
                                                class="font-size-48 ">{{ item.discounts
                                                }}</span>折</div>
                                    </div>
                                    <div class="divider"></div>
                                    <div class="info-box">
                                        <div>有效期：{{ item.startData }} 至 {{ item.endData }} </div>
                                        <div v-if="item.typeCodeName == '兑换券'">兑换物品：{{ item.goodsName }}</div>
                                        <div>使用限制：
                                            <span class="color-FF6A00" v-if="item.priceUseCondition == '0'">任意金额可用，</span>
                                            <span class="color-FF6A00" v-else-if="item.priceUseCondition == '1'">满{{
                                                item.useAmt
                                            }}可用，</span>
                                            <span class="color-FF6A00" v-else-if="item.priceUseCondition == '2'">每满{{
                                                item.useAmt }}可用，</span>
                                            <span class="color-FF6A00" v-if="item.useCondition == 0">无限制</span>
                                            <span class="color-FF6A00" v-else-if="item.useCondition == 1">每张桌台限用{{
                                                item.roomUseNum
                                            }}张</span>
                                            <span class="color-FF6A00" v-else-if="item.useCondition == 2">每个会员限用{{
                                                item.memberUseNum
                                            }}张</span>
                                            <span class="color-FF6A00"> ，优惠{{ item.isDiscountSharing == "1" ? '不' : ''
                                            }}可共享</span>
                                        </div>
                                        <div>不可用原因：<span class="color-FF6A00">{{ item.useerrmsg }}</span></div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>

                </div>
                <div class="footer-box">
                    <el-button class="cancel" @click="handleCancel">取消</el-button>
                    <el-button class="submit" @click="handleSubmit">确认</el-button>
                </div>
            </el-dialog>
        </div>

        <div class="dialog-box-code">
            <el-dialog class="dialog" top="80px" v-model="visible" draggable overflow :close-on-click-modal="true"
                :close-on-press-escape="false" :show-close="false">
                <div class="content">
                    <div>请扫码</div>
                    <el-input ref="input_qrcode" type="password" class="input-qrcode" v-model="form.encryptData"
                        :autofocus="true" @keyup.enter.native="enterQrcode" />
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script setup >
import { formatDecimal } from '@/utils/chenhao'
import Api from '@/api'
import ls from "@/lib/ls";
import useConfigStore from '@/store/config'
const configStore = useConfigStore()
// 接收父组件参数 props
const props = defineProps({
    tableInfo: {
        type: Object,
        required: false,
    },
    selectWares: {
        type: Array,
        required: false,
    },
    received: {
        type: String,
        required: false,
    },
    form: {
        type: Object,
        required: false,
    },
    price: {
        type: String,
        required: false,
    },
    unpay: {
        type: String,
        required: false,
    },
    payData: {
        type: Array,
        required: false,
    },
    saleData: {
        type: Array,
        required: false,
    },
    details: {
        type: Array,
        required: false,
    },
    vipPrice: {
        type: String,
        required: false,
    },
    vipInfo: {
        type: Object,
        required: false,
    },
    coinsPrice: {
        type: String,
        required: false,
    },
    marketUserName:{
        type: String,
        required: false,
    },
    marketUser:{
        type: String,
        required: false,
    }
})
const shopInfo = useConfigStore().shopInfo
const tableInfo = toRef(props, 'tableInfo')
const selectWares = toRef(props, 'selectWares')
const received = toRef(props, 'received')
const price = toRef(props, 'price')
const unpay = toRef(props, 'unpay')
const form = toRef(props, 'form')
const payData = toRef(props, 'payData')
const saleData = toRef(props, 'saleData')
const details = toRef(props, 'details')
const vipPrice = toRef(props, 'vipPrice')
const vipInfo = toRef(props, 'vipInfo')
const coinsPrice = toRef(props, 'coinsPrice')
const marketUserName = toRef(props, 'marketUserName')
const marketUser = toRef(props, 'marketUser')
watch(() => unpay.value, (newvalue, oldvalue) => {
    form.value.payAmt = newvalue
})

const emit = defineEmits(['focusForm'])
// 数字键盘
let tooPrice = ref(0)

const focusForm = (str) => {
    // keyboard.value = true
    emit('focusForm', str)
    tooPrice.value = unpay.value
}
const blurForm = (params) => {
    console.log(params)
    switch (params) {
        case 'coin':
            // 如果金币加会员余额收款 大于 待付金额 (要计算金币和余额各取多少)
            if(Number(form.value.payAmt_coins) + Number(form.value.payAmt)  > Number(unpay.value)){
                if(Number(form.value.payAmt_coins) >= Number(unpay.value)){
                    form.value.payAmt_coins = unpay.value
                }
                form.value.payAmt = Number(tooPrice.value) - Number(form.value.payAmt_coins)
            }
            break;
    
        case 'member':
            // 如果金币加会员余额收款 大于 待付金额
            if(Number(form.value.payAmt_coins) + Number(form.value.payAmt)>= Number(unpay.value)){
                if(Number(form.value.payAmt) >= Number(unpay.value)){
                    form.value.payAmt = unpay.value
                }
                form.value.payAmt_coins = Number(tooPrice.value) - Number(form.value.payAmt)
            }
            break;
    }
    
    // keyboard.value = false
}

onMounted(() => {
    if (form.value.mobile && form.value.mobile.length > 0) {
        handleSearch()
    }
})

// 查询会员
let vip = ref({})
let isVip = ref(false)
let card_options = ref([])
let ticket_options = ref([])
let currentCardIndex = ref(0)
const handleSearch = async () => {
    visible.value = false
    if (!form.value.mobile && !form.value.encryptData) return
    // console.log(mobile.value)
    const data = {
        mobile: form.value.mobile,
        encryptData: form.value.encryptData,
    }
    await Api.Common.PcObjProcess.Do({ "functionName": "GetMemberInfo", "orgCode": "0004", "contentData": data })
        .then(res => {
            console.log('搜索会员res :>> ', res);
            if (res.result == '') return ElNotification({
                title: '提示',
                message: '没有搜索到会员',
                type: 'warning',
            })
            vip.value = res
            card_options.value = res.cardList
            form.value.cardNo = res.cardList[0].cardNo
            getTicket()
        })
}

const setVipInfo = () => {
    console.log(card_options.value)
    console.log(payData.value);
    
    
    card_options.value.forEach(item => {
        if (item.memberIsPayCard == 1) {
            if(shopInfo.IsPriceVipPrice){
                if(item.currentAmt <= 0 || (payData.value && payData.value.length > 0)){
                    return
                }
            }
            vipInfo.value.hasVipPrice = true
            // console.log('vipInfo.value.isDiscountSharing:>> ', vipInfo.value.isDiscountSharing );
            if (vipInfo.value.isDiscountSharing == '1') return
            vipInfo.value.priceType = '2'
            if (Number(price.value) == Number(vipPrice.value)) return
            let flag = false
            saleData.value.forEach((item, $index) => {
                if (item.yhxm == '会员折扣优惠') {
                    flag = true
                }
            });
            if (!flag) {
                const saleObj = {
                    yhxm: '会员折扣优惠',
                    je: Number(formatDecimal(price.value - vipPrice.value)) ,
                    code: tableInfo.value.payBatchCode,
                    amt: Number(formatDecimal(price.value - vipPrice.value)) ,
                    type: '会员折扣优惠',
                    subType: '',
                }
                saleData.value.push(saleObj)
            }
        }
    })
    // if (card_options.value[currentCardIndex.value].memberIsPayCard == 1) {

    // } else {
    //     vipInfo.value.hasVipPrice = false
    //     vipInfo.value.priceType = '1'
    //     saleData.value.forEach((item, index) => {
    //         if (item.yhxm == '会员折扣优惠') {
    //             saleData.value.splice(index, 1)
    //         }
    //     })
    // }
}

const changeCardNo = (v) => {
    // console.log('v :>> ', v);
    card_options.value.forEach((item, index) => {
        if (item.cardNo == v) {
            currentCardIndex.value = index
        }
    });
    // console.log('card_options.value[currentCardIndex.value].memberIsPayCard :>> ', card_options.value[currentCardIndex.value].memberIsPayCard);
    // setVipInfo()
    getTicket()
}

// 获取优惠券
let canUseNum = ref(0)
let cannotUseNum = ref(0)
let roomuselist = ref([])
let ticketUseList = ref([])
let ticketUseTypeList = ref([])
let goodsTicketList = ref([]) // 本单可用兑换券的商品数组
const getTicket = async (params) => {
    resetTicketForm()
    // let goods = selectWares.value.map(item => {
    //     return item
    // })
    if (!card_options.value && !card_options.value[currentCardIndex.value].cardNo) return
    if ((!selectWares.value || selectWares.value.length == 0) || !tableInfo.value.consumeCode) return
    isVip.value = false
    card_options.value.forEach(item => {
        if (item.memberIsPayCard == 1) {
            isVip.value = true
        }
    })
    let data = {
        isVip:isVip.value,
        memberCarCode: card_options.value[currentCardIndex.value].cardNo,
        consumeCode: tableInfo.value.consumeCode,
        orderDetails: JSON.stringify(selectWares.value),
    }
    console.log('查询优惠券前的data :>> ', data);
    return await Api.Common.PcObjProcess.Do({ "functionName": "GetMenberTicket", "orgCode": "0004", "contentData": data })
        .then(res => {
            console.log('查询优惠券res :>> ', res);
            goodsTicketList.value = res.orderStatistics
            ticket_options.value = res.ticketList.map(item => {
                return {
                    ...item,
                    checked: false,
                }
            })
            canUseNum.value = 0
            cannotUseNum.value = 0
            ticket_options.value.forEach(item => {
                if (item.isUse) {
                    canUseNum.value += 1
                } else {
                    cannotUseNum.value += 1
                }
            })
            roomuselist.value = res.roomuselist
            ticketUseList.value = res.ticketUseList
            ticketUseTypeList.value = res.ticketUseTypeList

            vipInfo.value.isDiscountSharing = '0'
            roomuselist.value.forEach((item, $index) => {
                if (item.isDiscountSharing == '1') {
                    vipInfo.value.isDiscountSharing = '1'
                }
            });
            // console.log('vipInfo.value.isDiscountSharing:>> ', vipInfo.value.isDiscountSharing );
            setVipInfo()
        })
}

// 父组件小键盘点击确定
const handleKeyboardConfirm = async(params) => {
    
    if (!form.value.cardNo){
        ElNotification({
            title: '提示',
            message: '请选择会员卡',
            type: 'warning',
        })
        return 
    } 
    if (unpay.value <= 0){
        ElNotification({
            title: '提示',
            message: '收款金额为0无法收款',
            type: 'warning',
        })
        return 
    } 
    if (Number(form.value.payAmt) > Number(unpay.value)){
        ElNotification({
            title: '提示',
            message: '收取金额不能大于收款金额',
            type: 'warning',
        })
        return 
    }
    if (!form.value.payAmt && !form.value.payAmt_coins){
        ElNotification({
            title: '提示',
            message: '请输入收取金额或者金币金额',
            type: 'warning',
        })
        return 
    }
    if (Number(form.value.payAmt_coins) > card_options.value[currentCardIndex.value].currentCoins){
        ElNotification({
            title: '提示',
            message: '使用金币金额不能大于卡内金余额',
            type: 'warning',
        })
        return 
    }
    if (Number(form.value.payAmt_coins) > Number(coinsPrice.value)){
        ElNotification({
            title: '提示',
            message: '使用金币金额不能大于最多可使用金币金额',
            type: 'warning',
        })
        return
    }
    if (Number(form.value.payAmt_coins) + Number(form.value.payAmt) > Number(unpay.value)){
        ElNotification({
            title: '提示',
            message: '金币金额+收取金额不能大于收款金额',
            type: 'warning',
        })
        return 
    }
    configStore.payFlag = true // 支付开关
    // 处理勾选的商品
    let detailList = []
    if (details.value.length > 0) {
        detailList = details.value
    } else {
        console.log(selectWares.value);
        let toolArr = []
        selectWares.value.forEach(item=>{
            toolArr.push(item)
            if (item.subGoods && item.subGoods.length > 0) {
                toolArr.push(...item.subGoods)
            }
        })
   
        console.log(toolArr);
        
        detailList = toolArr.map(item => {
            return item.itemCode
        })
    }
    // 会员卡支付
    if (form.value.payAmt && form.value.payAmt > 0) {
        console.log(selectWares.value);
        console.log(isVip.value);
        
        const sendAmtForm = {
            amt:price.value ,// 当前订单金额
            payAmt:form.value.payAmt, // 本次支付金额
            cardNo:form.value.cardNo ,// 会员卡号
            isVipPay:isVip.value ? '1':'0' ,// 是否会员权益支付 0 否 1是
            goods:JSON.stringify(selectWares.value) ,// 商品信息
        }
        console.log(sendAmtForm);
        
        if(isVip.value){
            sendAmtForm.amt = vipPrice.value
        }
        let prePayAmt = 0
        let payPreAmtRate = 0
        // 获取赠送金额
        await Api.Common.PcObjProcess.Do({
            functionName: 'GetPrePayAmt',
            contentData: sendAmtForm
        }).then(res=>{
            prePayAmt = res.payPreAmt
            payPreAmtRate = res.payPreAmtRate
        }).catch(err=>{
            console.log(err);
            
        })
        let obj = {}
        if(prePayAmt >= form.value.payAmt){
            obj = {
                zffs: form.value.actionType,
                skje: formatDecimal(form.value.payAmt),
                consumeCode: form.value.consumeCode,
                payType: '004',
                totalAmt: unpay.value,
                payAmt: 0,
                prePayAmt:form.value.payAmt,
                payPreAmtRate:payPreAmtRate,
                memberCode: vip.value.memberCode,
                memberName: vip.value.memberName,
                memberMobile: vip.value.mobile,
                memberOpenId: vip.value.openId,
                cardNo: form.value.cardNo,
                ticketCode: form.value.ticketCode,
                detailList,
            }
        }else{
            obj = {
                zffs: form.value.actionType,
                skje: formatDecimal(form.value.payAmt),
                consumeCode: form.value.consumeCode,
                payType: '004',
                totalAmt: unpay.value,
                payAmt: formatDecimal(form.value.payAmt - prePayAmt),
                prePayAmt:prePayAmt,
                payPreAmtRate:payPreAmtRate,
                memberCode: vip.value.memberCode,
                memberName: vip.value.memberName,
                memberMobile: vip.value.mobile,
                memberOpenId: vip.value.openId,
                cardNo: form.value.cardNo,
                ticketCode: form.value.ticketCode,
                detailList,
            }
        }

        
        const data = {
            payType: '004',
            consumeCode: tableInfo.value.consumeCode,
            roomCode: tableInfo.value.roomCode,
            payBatchCode: tableInfo.value.payBatchCode,
            orderAmt: price.value,
            realPayAmt: form.value.payAmt,
            detailList: detailList.join(','),
            payList: [obj],
            serviceAmt: saleData.value
        }
        await Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "orgCode": "0004", "contentData": data })
            .then(res => {
                console.log('买单确认res :>> ', res);
                obj.itemCode = res.itemCode
                obj.payBatchCode = res.payBatchCode
                tableInfo.value.payBatchCode = res.payBatchCode
                payData.value.push(obj)
                form.value.payAmt = ''
                ls.set('payBatchCode', res.payBatchCode)
                configStore.ispaying.id ++
            })
            .catch(err=>{
                console.log(err);
                
                configStore.ispaying.id ++
            })
    }
    // 金币支付
    if (form.value.payAmt_coins && form.value.payAmt_coins > 0) {
        const obj = {
            zffs: '金币支付',
            skje: formatDecimal(form.value.payAmt_coins),
            consumeCode: form.value.consumeCode,
            payType: '013',
            totalAmt: unpay.value,
            payAmt: form.value.payAmt_coins,
            memberCode: vip.value.memberCode,
            memberName: vip.value.memberName,
            memberMobile: vip.value.mobile,
            memberOpenId: vip.value.openId,
            cardNo: form.value.cardNo,
            ticketCode: form.value.ticketCode,
            detailList,
        }
        const data = {
            payType: '013',
            consumeCode: tableInfo.value.consumeCode,
            roomCode: tableInfo.value.roomCode,
            payBatchCode: tableInfo.value.payBatchCode,
            orderAmt: price.value,
            realPayAmt: form.value.payAmt_coins,
            detailList: detailList.join(','),
            payList: [obj],
            serviceAmt: saleData.value
        }
        await Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "orgCode": "0004", "contentData": data })
            .then(res => {
                console.log('金币买单确认res :>> ', res);
                obj.itemCode = res.itemCode
                obj.payBatchCode = res.payBatchCode
                tableInfo.value.payBatchCode = res.payBatchCode
                payData.value.push(obj)
                form.value.payAmt_coins = ''
                ls.set('payBatchCode', res.payBatchCode)
                configStore.ispaying.id ++
            })
            .catch(err=>{
                console.log(err);
                
                configStore.ispaying.id ++
            })
    }
}

// 选择优惠券弹窗
let ticketVisible = ref(false)
const handleTicket = (params) => {
    const hasPayType012 = payData.value.some(item => item.payType == "012");
    if(hasPayType012){
        ElNotification({
            title: '提示',
            message: '已使用优惠券，请撤销先前优惠券后再重新选择',
            type: 'warning',
        })
        return
    }
    if (!vip.value.memberCode) return ElNotification({
        title: '提示',
        message: '请先验证会员',
        type: 'warning',
    })
    ticketVisible.value = true
    goodsTicketList.value.forEach(v=>{
        v.isCanUseMore = true // 可以使用兑换券优惠券
    })  
}

const handleCancel = (params) => {
    ticketVisible.value = false
}
// 确认优惠券弹窗
const handleSubmit = async (params) => {
    // console.log('checkedList.value :>> ', checkedList.value);
    const nameList = checkedList.value.map(item => item.goodsName)
    form.value.ticketName = nameList.join(',')
    const codeList = checkedList.value.map(item => item.code)
    form.value.ticketCode = codeList.join(',')
    await order()
    // 处理勾选的商品
    let detailList = []
    console.log('details.value :>> ', details.value);
    if (details.value.length > 0) {
        detailList = details.value
    } else {
         console.log(selectWares.value);
        let toolArr = []
        selectWares.value.forEach(item=>{
            toolArr.push(item)
            if (item.subGoods && item.subGoods.length > 0) {
                toolArr.push(...item.subGoods)
            }
        })
   
        console.log(toolArr);
        
        detailList = toolArr.map(item => {
            return item.itemCode
        })
      
        
    }
    const obj = {
        zffs: '会员优惠券',
        skje: formatDecimal(checkedAmt.value),
        consumeCode: form.value.consumeCode,
        payType: '012',
        totalAmt: unpay.value,
        payAmt: checkedAmt.value,
        memberCode: vip.value.memberCode,
        memberName: vip.value.memberName,
        memberMobile: vip.value.mobile,
        memberOpenId: vip.value.openId,
        cardNo: form.value.cardNo,
        ticketCode: form.value.ticketCode,
        detailList,
    }
    isVip.value = false
    card_options.value.forEach(item => {
        if (item.memberIsPayCard == 1) {
            isVip.value = true
        }
    })
    const data = {
        payType: '012',
        consumeCode: tableInfo.value.consumeCode,
        roomCode: tableInfo.value.roomCode,
        payBatchCode: tableInfo.value.payBatchCode,
        orderAmt: price.value,
        realPayAmt: checkedAmt.value,
        detailList: detailList.join(','),
        payList: [obj],
        serviceAmt: saleData.value,
        isVip:isVip.value,
        memberCarCode: card_options.value[currentCardIndex.value].cardNo,
        itemCode: detailList.join(','),
        memberTicketCode: form.value.ticketCode,
        // consumeCode: form.value.consumeCode,
        roomCode: tableInfo.value.roomCode,
        memberMobile: vip.value.mobile,
    }
    console.log('data :>> ', JSON.stringify({ "functionName": "UseMenberTicket", "orgCode": "0004", "contentData": data }));
    // return
    Api.Common.PcObjProcess.Do({ "functionName": "UseMenberTicket", "orgCode": "0004", "contentData": data })
        .then(res => {
            console.log('使用优惠券 res :>> ', res);
            if (res.list && res.list.length > 0) {
                res.list.forEach(item => {
                    obj.zffs = item.ticketName
                    obj.skje = item.ticketAmt
                    obj.itemCode = item.itemCode
                    obj.payBatchCode = item.payBatchCode
                    obj.isDiscountSharing = item.isDiscountSharing
                    tableInfo.value.payBatchCode = item.payBatchCode
                    const nobj = { ...obj }
                    payData.value.push(nobj)
                    ls.set('payBatchCode', item.payBatchCode)
                })
                ticketVisible.value = false
                getTicket()
            }
            // obj.itemCode = detailList.join(',')
            // obj.payBatchCode = tableInfo.value.payBatchCode
            // payData.value.push(obj)
            // form.value.payAmt = ''
        })
}

// 打勾优惠券
import { rule_share, rule_count, rule_amt } from './ticketRules'
let checkedList = ref([])
let checkedAmt = ref(0)
const handleCheckedTicket = (item) => {
    console.log('item :>> ', item);
    // 判断如果是取消勾选就不进入之后的验证
    if (item.checked) {
        item.checked = !item.checked
        checkedAmt.value -= Number(item.deductionAmt)
        checkedAmt.value = formatDecimal(checkedAmt.value)
        checkedList.value.forEach((i, $index) => {
            if (i.code == item.code) {
                checkedList.value.splice($index, 1);
            }
        })
        goodsTicketList.value.forEach(v=>{
            if(v.goodsCode == item.goodsCode){
                v.orderQty += Number(item.goodsCount)
                if(v.orderQty > 0){
                    v.isCanUseMore = true
                }
                
            }
        })
        console.log('checkedList.value :>> ', checkedList.value);
        return
    }
    console.log(checkedAmt.value,unpay.value);
    if(Number(checkedAmt.value) >= Number(unpay.value)){
        ElNotification({
            title: '提示',
            message: '优惠券金额已超出待付金额',
            type: 'warning',
        })
        return  
    }

    // 判断兑换券是否可用
    goodsTicketList.value.forEach(v=>{
        if(v.goodsCode == item.goodsCode && !v.isCanUseMore){
            ElNotification({
                title: '提示',
                message: '兑换券使用数量已到上限',
                type: 'warning',
            })
            return   
        }
    })

    //  checkedList.value, ticketUseList.value, ticketUseTypeList.value
    // 验证优惠共享
    const rule_share_res = rule_share(item, checkedList.value, roomuselist.value, vipInfo.value.priceType)
    console.log('rule_share_res :>> ', rule_share_res);
    if (!rule_share_res.flag) return ElNotification({
        title: '提示',
        message: rule_share_res.errMsg,
        type: 'warning',
    })

    // 验证 金额限制条件 不限制 满 每满
    const rule_amt_res = rule_amt(item, checkedList.value, roomuselist.value, ticketUseList.value,)
    console.log('rule_amt_res :>> ', rule_amt_res);
    if (!rule_amt_res.flag) return ElNotification({
        title: '提示',
        message: rule_amt_res.errMsg,
        type: 'warning',
    })

    // 验证桌台或者会员使用数量
    const rule_count_res = rule_count(item, checkedList.value, ticketUseList.value, ticketUseTypeList.value)
    console.log('rule_count_res :>> ', rule_count_res);
    if (!rule_count_res.flag) return ElNotification({
        title: '提示',
        message: rule_count_res.errMsg,
        type: 'warning',
    })

    // 验证兑换券的使用
    goodsTicketList.value.forEach(v=>{
        if(v.goodsCode == item.goodsCode){
            v.orderQty -= Number(item.goodsCount)
            if(v.orderQty <= 0)
            v.isCanUseMore = false
        }
    })

    item.checked = !item.checked
    checkedList.value.push(item)

    let toolAllAmt = price.value // 本次订单金额
    let toolPrice = 0 // 工具(过渡用)
    console.log(checkedList.value);
    checkedList.value.forEach(item => {
            if(item.typeCode == '2'){
                console.log(item);
                // 多张折扣券的计算金额得在之前的基础上打折 如8折后的金额再打8折
                item.deductionAmt = Number(toolAllAmt) * (1 - (Number(item.discounts)/ 10)) 
                toolAllAmt = toolAllAmt - item.deductionAmt
                console.log(item.deductionAmt);
            }
            console.log(item.deductionAmt);
            console.log(checkedAmt.value);
            toolPrice += Number(item.deductionAmt)
            console.log(checkedAmt.value);
        })

    checkedAmt.value = formatDecimal(toolPrice)
    console.log('checkedList.value :>> ', checkedList.value);
    return
    // ------------------验证兑换券的--------------------
    // 判断如果是取消勾选就不进入之后的验证
    if (item.checked) {
        returnCheckedTicket(item, ticketUseList.value, selectWares.value, checkedList.value)
        item.checked = !item.checked
        checkedAmt.value -= (+item.ticketAmt)
        return
    }

    // 验证桌台使用限制
    let res1 = table_use(item, ticketUseList.value, selectWares.value)
    console.log('res1 :>> ', res1);
    if (!res1.flag) return ElNotification({
        title: '提示',
        message: res1.errMsg,
        type: 'warning',
    })
    // 验证会员使用限制
    let res2 = menber_use(item, ticketUseList.value, selectWares.value)
    console.log('res2 :>> ', res2);
    if (!res2.flag) return ElNotification({
        title: '提示',
        message: res2.errMsg,
        type: 'warning',
    })

    // console.log('ticketUseList.value :>> ', ticketUseList.value);
    // 验证n个商品用的券不能超过n张
    let res3 = count_use(item, checkedList.value, selectWares.value)
    console.log('res3 :>> ', res3);
    if (!res3.flag) return ElNotification({
        title: '提示',
        message: res3.errMsg,
        type: 'warning',
    })

    item.checked = !item.checked
    // checkedAmt.value = 0
    // console.log('push :>> ',);
    checkedList.value.push(item)
    checkedAmt.value += (+item.ticketAmt)
    console.log('checkedList.value :>> ', checkedList.value);
}

// 初始化已选优惠卷信息
const resetTicketForm = (params) => {
    checkedList.value = []
    checkedAmt.value = 0
    form.value.ticketName = ""
    form.value.ticketCode = ""
}

// 监听勾选的未结账商品
watch(selectWares, (newVal, oldVal) => {
    console.log('监听selectWares :>> ', selectWares);
    if (!form.value.cardNo) return
    getTicket()
}, { deep: true })

// 下单接口
const isAdd = ref(false);
const router = useRouter();
// 获取缓存里的菜单用来判断是否是点餐路由跳转来的,如果是就要下单
const order = async (params) => {
    const waresOrder = ls.get("WARES_ORDER") || [];
    if (waresOrder && waresOrder.length > 0) {
        waresOrder.forEach(ware => {
            if (ware.subGoods && ware.subGoods.length > 0) {
                console.log('11111 :>> ', 11111);
                ware.subGoods.forEach(item => {
                    waresOrder.push({
                        ...item,
                        goodsPriceCode: item.packageCode,
                        itemType: "3",
                        doType: "add",
                    })
                });
            }
        })
        isAdd.value = true;
        let router_orderBatchCode = router.currentRoute.value.query.orderBatchCode
        let contentData = {
            consumeCode: ls.get("TABLE_INFO").consumeCode,
            roomCode: ls.get("TABLE_INFO").roomCode,
            // consumeCode: "0004202402050006",
            // roomCode: "0004003",
            operType: "",
            detail: waresOrder,
            orderBatchCode: router_orderBatchCode,
            payType: '2',
        };
        // let contentData = {
        //     consumeCode: ls.get("TABLE_INFO").consumeCode,
        //     roomCode: ls.get("TABLE_INFO").roomCode,
        //     // consumeCode: "0004202402050006",
        //     // roomCode: "0004003",
        //     operType: "",
        //     detail: waresOrder,
        //     payType: '2',
        // };
        console.log("waresOrder :>> ", waresOrder);

        calculateOrderQty(contentData.detail)
        contentData.marketUserName = marketUserName.value
        contentData.marketUser = marketUser.value
        // return
        await Api.Common.PcObjProcess.Do({
            functionName: "orderAdd",
            contentData,
        }).then((res) => {
            console.log("下单 res :>> ", res);
            res.dataList.forEach((item) => {
                details.value.push(item.itemCode)
            });
            console.log('details :>> ', details.value);
            ls.remove("WARES_ORDER");
        });
    }
};

const visible = ref(false)
const input_qrcode = ref()
const handleCode = () => {
    form.value.encryptData = ""
    visible.value = true
    console.log('input_qrcode :>> ', input_qrcode);
    setTimeout(() => { input_qrcode.value.focus() }, 100)
    // nextTick(() => {

    // })
}
const enterQrcode = () => {
    console.log('enterQrcode', form.value.encryptData)
    handleSearch()
}
// 暴露方法给父组件
defineExpose({ handleKeyboardConfirm, getTicket })


// 套餐子项数量调整
function calculateOrderQty(items) {
    // 首先按 indexStr 分组
    const groupedItems = {};
    items.forEach(item => {
        if (!groupedItems[item.indexStr]) {
            groupedItems[item.indexStr] = [];
        }
        groupedItems[item.indexStr].push(item);
    });

    // 处理每个分组
    for (const indexStr in groupedItems) {
        const group = groupedItems[indexStr];
        let itemType2OrderQty = null;

        // 找到itemType为2的对象，并记录其orderQty
        group.forEach(item => {
            if (item.itemType == '2') {
                itemType2OrderQty = item.orderQty;
            }
        });

        if (itemType2OrderQty != null) {
            // 计算其它对象的orderQty乘以itemType为2的对象的orderQty
            group.forEach(item => {
                if (item.itemType == '3') {
                    item.orderQty = Number(itemType2OrderQty) * Number(item.orderQty);
                }
            });
        }
    }

    return items;
}
</script>

<style scoped lang="scss">
.form-box {
    margin-top: 5px;
    height: 300px;
    overflow-y: auto;
    overflow-x: hidden;
    ::v-deep {
        .el-input__wrapper {
            background: #F9F9F9;
            border-radius: 8px;
            border: 0;
            font-size: 12px;
            color: #999999;
        }
    }

    .margin-bottom-0 {
        ::v-deep {
            .el-form-item {
                margin-bottom: -1px;
            }
        }
    }

    .salaAmt {
        font-weight: 400;
        font-size: 16px;
        color: #FF3333;
    }

}
 .form-box::-webkit-scrollbar { 
            width:4px;
            height: 4px;
}

.form-box::-webkit-scrollbar-track {
background: #f1f1f1;
}

.form-box::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 10px;
}
.search-btn {
    font-weight: 400;
    font-size: 16px;
    color: #FF6A00 !important;
    width: 50px;
    // height: 50px;
    position: absolute;
    right: 40px;
    top: 0px;
}

.qrcode-img {
    width: 20px;
    height: 20px;
    position: absolute;
    right: 10px;
    top: 5px;
    cursor: pointer;
}

.vip-info-box {
    height: 30px;
    line-height: 30px;
    font-size: 12px;
    color: #212121;
}
.pd-vip-info {
    width: 100%;
    padding-left:30px;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: start;
    flex-wrap: wrap;
    .pd-vip-contiantr {
        width: 100%;
        display: flex;
        gap: 30px;
        div {
            height: 18px;
            line-height: 18px;
        }
        
    }
}
.not-info-vip {
    width: 100%;
    margin-top: 13px !important;
}
.margin-bottom-20 {
    margin-bottom: 10px;
}

.color-FF3333 {
    color: #FF3333;
}

.color-FF6A00 {
    color: #FF6A00;
}

.dialog-box {
    ::v-deep {
        .el-dialog__header {
            padding: 0;
        }

        .el-dialog {
            width: 860px;
            // height: 800px;
            background: #FFFFFF;
            border-radius: 16px;
            padding: 10px 30px;
        }
    }

    .footer-box {
        margin-top: 40px;
        display: flex;
        justify-content: center;
        align-items: center;

        .cancel {
            width: 160px;
            height: 60px;
            background: #FFFFFF;
            border-radius: 8px;
            border: 1px solid #FF6A00;
            font-size: 24px;
            color: #FF6A00;
        }

        .submit {
            width: 160px;
            height: 60px;
            background: #FF6A00;
            border-radius: 8px;
            font-size: 24px;
            color: #FFFFFF;
            margin-left: 30px;
        }
    }

    .dialog-content {

        .ticket-content {
            margin-top: 10px;
            height: 650px;
            overflow-y: auto;
            overflow-x: hidden;

            .ticket-box {
                margin-top: 10px;
                width: 800px;
                // height: 450px;
                background: #FAFAFA;
                border-radius: 16px;
                padding: 10px;

                .ticket {
                    // margin: 0 auto;
                    width: 780px;
                    // height: 100px;
                    background: #FFFBE5;
                    border-radius: 8px;
                    margin-bottom: 5px;
                    display: flex;
                    align-items: center;

                    .ticket-name-box {
                        width: 160px;
                        padding: 10px 0;
                        // height: 100px;
                        text-align: center;

                        .ticket-type {
                            font-family: PingFang SC;
                            font-weight: bold;
                            font-size: 18px;
                            color: #212121;
                        }

                        .ticket-wares {
                            margin-top: 15px;
                            font-family: PingFang SC;
                            font-weight: bold;
                            font-size: 24px;

                            .font-size-24 {
                                font-size: 24px;
                            }
                        }

                        .ticket-num {
                            .font-size-48 {
                                font-size: 48px;
                            }
                        }
                    }

                    .divider {
                        width: 1px;
                        height: 80px;
                        border-radius: 1px;
                        border: 1px solid #FFD400;
                    }

                    .info-box {
                        font-family: PingFang SC;
                        font-weight: 500;
                        font-size: 16px;
                        color: #212121;
                        height: 100px;
                        margin-left: 20px;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-between;
                        padding: 10px 0;
                        width: 540px;
                    }

                    .check-box {
                        ::v-deep {
                            .el-checkbox {
                                height: 40px;
                            }

                            .el-checkbox__inner {
                                width: 20px;
                                height: 20px;
                                border: 2px solid #666666;
                                border-radius: 4px;
                                background: #F9F9F9;
                            }

                            .is-checked {
                                .el-checkbox__label {
                                    color: #FF6A00;
                                }

                                .el-checkbox__inner {
                                    background: #F9F9F9;
                                }

                                .el-checkbox__inner {
                                    width: 20px;
                                    height: 20px;
                                    border: 2px solid #FF6A00;
                                    border-radius: 4px;
                                    // background: #FF6A00;
                                }

                                .el-checkbox__inner::after {
                                    border: 2px solid #FF6A00;
                                    border-left: 0;
                                    border-top: 0;
                                    left: 6px;
                                    top: 4px;
                                }
                            }
                        }
                    }
                }
            }
        }



        .unUse {
            -webkit-filter: grayscale(1);
            /* Chrome, Safari, Opera */
            filter: grayscale(1);
        }

        .dialog-title-row {
            display: flex;
            justify-content: space-between;

            .title {
                font-family: Microsoft YaHei;
                font-weight: bold;
                font-size: 20px;
                color: #212121;

                .num {
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    font-size: 18px;
                    color: #FF3333;
                }
            }

            .tip {
                font-family: Microsoft YaHei;
                font-weight: 400;
                font-size: 16px;
                color: #666666;
            }
        }
    }

}

.margin-top-10 {
    margin-top: 10px;
}

.margin-left-40 {
    margin-left: 20px;
}

.color-FF6A00 {
    color: #FF6A00;
}

.color-FF3333 {
    color: #FF3333;
}

.cursor-pointer {
    cursor: pointer;
}

.dialog-box-code {

    ::v-deep {
        .el-dialog {
            width: 300px;
            // height: 300px;
        }

        .el-dialog__header {
            padding-bottom: 0px;
        }
    }

    .content {
        height: 200px;
        font-size: 50px;
        display: flex;
        justify-content: center;
        align-items: center;

        .input-qrcode {
            position: absolute;
            opacity: 0;
            filter: alpha(opacity=0)
        }
    }
}
.jt-mt-tar {
    height: 20px;
    line-height: 20px;
}
.jt-mt-tar2 {
    position: relative;
  margin-top: 5px;
  height:25px;
  width: 180px;
  line-height:25px;
}
.jt-mt-text {
    position: absolute;
    right: 20px;
    top: 8px;
    left: 200px;
  }
  
</style>
